<?php

namespace app\shop\model\welfare;

use app\common\model\BaseModel;
use app\shop\model\user\User;

class Welfare extends BaseModel
{
    protected $name = 'user_welfare';
    public function user()
    {
        return $this->hasOne(User::Class);
    }

    public function welfares()
    {
        return $this->belongsTo(Welfares::Class,'type');
    }

    public function getList($params)
    {
        $where = array();
        if($params['type_id']){
            $where[] = ['type','=',$params['type_id']];
        }
        if($params['phone']){
            $where[] = ['phone','=',$params['phone']];

        }
        if($params['car_number']){
            $where[] = ['car_number','=',$params['car_number']];
        }
        if($params['reg_date']){
            $stime = strtotime($params['reg_date'][0].' 00:00:00');
            $etime = strtotime($params['reg_date'][1].' 23:59:59');
            $where[] = ['create_time','between',[$stime,$etime]];
        }

        $res =  $this->with(['user','welfares'])
            ->where($where)
            ->order('create_time desc')
            ->paginate($params, false, [
                'query' => request()->request()
            ]);
        //dump($this->getLastSql());die;
        return $res;
    }

    public function getMonth($params)
    {
        if($params['reg_date']){
            $timestamp = strtotime( $params['reg_date'] );
            $start_time = strtotime(date( 'Y-m-1 00:00:00', $timestamp ));
            $mdays = date( 't', $timestamp );
            $end_time = strtotime(date( 'Y-m-' . $mdays . ' 23:59:59', $timestamp ));


            $where[] = ['create_time','between',[$start_time,$end_time]];
        }else{
            $date = date("Y-m-d");
            $start_time = strtotime(date('Y-m-01 00:00:00', strtotime($date)));

            $end_time = strtotime(date('Y-m-d 23:59:59', strtotime("$start_time +1 month -1 day"))); //本月最后一天

            $where[] = ['create_time','between',[$start_time,$end_time]];
        }

        return $this->with(['user'])
            ->where($where)
            ->paginate($params, false, [
                'query' => request()->request()
            ]);
    }
    public function edit($data)
    {
        return $this->save($data);
    }

    public function get_count($type)
    {
        $times = date_time($type);
        $where[] = ['create_time','between',$times];
        $where[] = ['is_delete','=',0];
        $count = $this->where($where)->count();
        return $count;
    }

}